//
//  NetworkTools.swift
//  SwiftWB
//
//  Created by 钟清 on 17/3/29.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {
    /// 单例
    static let shareInstance: NetworkTools = {
        
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let instance = NetworkTools(baseURL: baseURL, sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
        /// 序列化
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set
        return instance
    }()

    /* 获取微博数据 */
    func loadStatusesData(since_id: String, max_id: String, finished: (array: [[String : AnyObject]]?, error: NSError?) -> ()) {
        /* 断言 */
        assert(UserAccount.loadUserAccount() != nil, "必须授权之后才能获取微博数据")
        /* 路径和参数 */
        let path = "2/statuses/home_timeline.json"
        let temp_id = (max_id != "0") ? "\(Int(max_id)! - 1)" : max_id
        let parameters = ["access_token" : UserAccount.loadUserAccount()!.access_token!,
                          "since_id" : since_id,
                          "max_id" : temp_id]
        /* 请求 */
        GET(path, parameters: parameters, success: { (task, objc) in
            /* 返回数据给调用者 */
            guard let array = (objc as! [String : AnyObject])["statuses"] as? [[String : AnyObject]] else {
                /* 情况一 */
                finished(array: nil, error: NSError(domain: "com.imooc.zq", code: 1000, userInfo: ["message" : "无法获得数据"]))
                return
            }
            /* 情况二*/
            finished(array: array, error: nil)
            
            }) { (task, error) in
                /* 情况三 */
                finished(array: nil, error: error)
        }
    }
    
    /* 发送微博 */
    //FIXME: ---
    func sendStatus(statusText: String, image: UIImage?, finished:(dict: [String : AnyObject]?, error: NSError?) -> ()) {
        var path = "/2/statuses/"
        let parameters = ["access_token" : UserAccount.loadUserAccount()!.access_token!,
                                "status" : statusText]
        if image == nil { // 发送微博不带图
            path += "update.json"
            POST(path, parameters: parameters, success: { (task, objc) in
                finished(dict: objc as? [String : AnyObject], error: nil)
                }, failure: { (task, error) in
                    finished(dict: nil, error: error)
            })
        } else { // 发送微博带图
            path += "upload.json"
            POST(path, parameters: parameters, constructingBodyWithBlock: { (formData) in
                /* 拼接图片 */
                let imageData = UIImagePNGRepresentation(image!)
                formData.appendPartWithFileData(imageData!, name: "pic", fileName: "123.png", mimeType: "image/png")
                }, success: { (task, objc) in
                    finished(dict: objc as? [String : AnyObject], error: nil)
                }, failure: { (task, error) in
                    finished(dict: nil, error: error)
            })
        }
    }  
}
